package main

import (
	"fmt"
)

type Student struct {
	Name string
	Sex  int
}

func main() {
	declareSlice()
	sliceOperator()
	subSlice()
}

func declareSlice() {
	//第一种方式实用切片 需要实用make函数
	var students []Student           //默认初始化为nil,长度为0
	students = make([]Student, 2, 2) //第二个参数表示长度，第三个参数表示容量(可选)
	students[0] = Student{Name: "张三", Sex: 1}
	students[1] = Student{Name: "李四", Sex: 0}

	//students[2] = Student{Name: "王五", Sex: 0} index out of
	fmt.Println("长度:", len(students), "容量", cap(students))

	students = append(students, Student{Name: "王五", Sex: 0})
	fmt.Println("实用append方法追加后长度:", len(students), "容量", cap(students))
	for index, value := range students {
		fmt.Println("index:", index, "value:", value)
	}
	//第二种方式实用切片
	stds := []Student{
		Student{Name: "张三", Sex: 1},
		Student{Name: "李四", Sex: 0},
		Student{Name: "王五", Sex: 0},
	}

	for index, value := range stds {
		fmt.Println("index:", index, "value:", value)
	}
}

/**切片常用操作*/
func sliceOperator() {
	stds := []Student{
		Student{Name: "张三", Sex: 1},
		Student{Name: "李四", Sex: 0},
		Student{Name: "王五", Sex: 0},
	}
	//求长度,容量
	fmt.Println("切片的长度:", len(stds), "切片的容量:", cap(stds))

	//追加元素
	stds = append(stds, Student{Name: "赵六", Sex: 1})
	//复制元素
	copys := make([]Student, len(stds), cap(stds))
	copy(copys, stds) //第一个参数是目标第二个参数是原
	for k, v := range copys {
		fmt.Println(k, v)
	}
	//批量追加元素
	stds = append(stds, copys...)
	for k, v := range stds {
		fmt.Println("批量", k, v)
	}
}

func subSlice() {
	stds := []Student{
		Student{Name: "王二", Sex: 0},
		Student{Name: "张三", Sex: 1},
		Student{Name: "李四", Sex: 0},
		Student{Name: "王五", Sex: 0},
		Student{Name: "赵六", Sex: 1},
		Student{Name: "孙七", Sex: 0},
	}
	//slice[start:end] 语法截取切片中的元素
	fmt.Println("start:", 0, "end:", 4, "数据为:", stds[0:4]) // [0,4) 前闭后开
	fmt.Println("start:", 2, "end:", 5, "数据为:", stds[2:5]) // [2,5) 前闭后开
	fmt.Println("数据:", stds[:])                            //全部数据
	fmt.Println("数据:", stds[0:])                           //全部数据
	fmt.Println("数据", stds[0:len(stds)])                   //全部数据
	fmt.Println("数据", stds[3:])                            // [3,len(stds)) 前闭后开
	fmt.Println("数据", stds[:4])                            // [0,4) 前闭后开
}
